/**
 * Created by yanyuan on 2015/1/14.
 */
'use strict';

angular.module('myApp.MessageView', ['myApp.MessageModel','myApp.Manager','myApp.MessageHandler', 'myApp.ChatHandler','myApp.GroupHandler', 'myApp.ContactHandler', 'myApp.OrganizationHandler']).
    factory("MessageView", ['$rootScope','Message','MessageManager','ChatHandler', 'GroupHandler', 'ContactHandler', 'OrganizationHandler',
        function ($rootScope,Message,MessageManager,ChatHandler,GroupHandler,ContactHandler,OrganizationHandler) {
            $rootScope.messages = [];
            $rootScope.userChats = {};
            $rootScope.chatContainerStyle = null;
            $rootScope.$on('ngMessageRepeatFinished', function () {
                util.chatScorllTop();
            });

            function receiveChatMessage(message) {
                message = message.content;
                if(message.from == message.to){//自己发送的消息不保存
                    return;
                }
                if (MessageManager[message.msgType] == null) {
                    return;
                }
                if (!MessageManager.messageSourceIsValid(message)) {
                    return;
                }
                if ($rootScope.voiceStatu) {
                    util.msgPlay();
                }
                //接收时消息列表显示标记
                switch (message.msgType){
                    case 12 :
                        message.content = '[图片]';
                        break;
                    case 13 :
                        message.voiceContent = message.content;
                        message.content = '[语音]';
                        break;
                    case 18 :
                        message.content = '[文件]';
                        break;
                }
      
                MessageManager[message.msgType].receive(message);
                if (MessageManager.isCurrChatMsg(message)) {
                    $rootScope.messages.push(message);
                }
                MessageManager.saveMessage(message);
                if (message.group) {//群消息显示
                    if (GroupHandler.groupIsExist(message.to)) {
                        var chatObj = ChatHandler.addChat(ChatHandler.message2Chat(message));
                        webNotification(chatObj);
                    } else {
                        GroupHandler.queryGroupPromise({'groupUid': message.to}).then(function (group) {//执行成功
                            GroupHandler.saveGroup(group);
                            GroupHandler.refreshGroup();
                            var chatObj =  ChatHandler.addChat(ChatHandler.message2Chat(message));
                            webNotification(chatObj);
                        }, function (errorMessage) {//执行失败
                            swal({title: errorMessage, timer: 2000});
                            return;
                        });
                    }
                } else {//个人消息显示
                    var chatObj = ChatHandler.addChat(ChatHandler.message2Chat(message));
                    webNotification(chatObj);
                }
            }

            function receiveResponseMessage(message) {
                message = message.content;
                switch (message.code) {
                    case 101 :
                        //隐藏发送消息加载
                        var messages = util.countMessage(MessageManager.getAllMessage(),$rootScope.messages, message.id, $rootScope.chatsMap);
                        MessageManager.saveAllMessage(messages);
                        break;
                    case 141 : window.location = 'login.do'; break;//未认证
                    case 142 : window.location = 'login.do'; break;//未登录
                    case 143 : window.location = 'login.do'; break;//未知错误
                    case 301 : window.location = 'login.do'; break;//在别处登录
                    case 302 : window.location = 'login.do'; break;//重复登录
                    case 310 : window.location = 'login.do'; break;//注销
                    case 3101 :
                        //console.log('websocket 验证Token成功！');
                        break;
                    case 3102 : swal('Session验证不通过，请重新登录！'); window.location = 'login.do'; break;//Session验证不通过
                }
            }

            function receiveCommandMessage(message) {
                message = message.content;
                if (!message.commType) {
                    return;
                }
                switch (message.commType) {//commType 20 人员信息变更-离线消息，52:群组加人, 53:群组踢人, 55:人员信息变更, 71:群消息修改
                    case 20 : updateContactInfoOffline(message); break;
                    case 52 : addGroupContact(message); break;
                    case 53 : delGroupContact(message); break;
                    case 55 : updateContactInfo(message); break;
                    case 71 : updateGroupInfo(message); break;
                }
                refresh();
            }

            var updateContactInfoOffline = function(message){
//                console.log(message);
//                console.log('人员信息变更-离线消息');
            }

            //接收消息处理
            function receiveMsg(message, callback) {
                switch (message.type) {//message.type 1:聊天信息 4:响应消息 5:命令消息
                    case 1 :
                        receiveChatMessage(message);
                        //ADD-TODO 语音消息暂时不发回执
                        if(message.content && message.content.msgType != 13) sendReceipt(message, callback);
                        break;
                    case 4 : receiveResponseMessage(message); break;
                    case 5 : receiveCommandMessage(message); sendReceipt(message, callback); break;
                }
            }

            //发送回执消息
            function sendReceipt(message, callback) {
                if(callback && angular.isFunction(callback)){
                    callback(new Message.ReceiptMessage(message.content.id));
                }
            }

            function updateGroupInfo(message) {
                GroupHandler.queryGroupPromise({groupUid : message.groupId}).then(function(group){
                    GroupHandler.saveGroup(group);
                    ChatHandler.updateChat({identifier : group.identifier, name : group.name});
                    if($rootScope.currentChatObj) $rootScope.currentChatObj = GroupHandler.getGroupByIdentifier($rootScope.currentChatObj.identifier);
                });
            }

            function updateContactInfo(message) {
                var params = {msgId: message.id, notifyType: message.commType, action: message.action, ids: message.userIds.join(',')};
                MessageManager.queryChangInfoPromise(params).then(function (data) {
                    var contacts = data.result.dataType;
                    angular.forEach(contacts, function (contact) {
                        contact.identifier = contact.username;
                        contact.deptId = contact.department;
                    });
                    switch (message.action) {
                        case 'ADD' : saveContacts(contacts); break;
                        case 'UPDATE' : updateContacts(contacts); break;
                        case 'DEL' : deleteContacts(contacts); break;
                    }
                }, function (errorMsg) {
                    //console.log(errorMsg);
                });
            }

            function refresh(){
                GroupHandler.refreshGroup();
                ContactHandler.refreshContact();
                ChatHandler.refreshChat();
                OrganizationHandler.refreshOrganization();
            }

            function saveContacts(contacts) {
                angular.forEach(contacts, function (contact) {
                    ContactHandler.saveContact(contact);
                    //update dept membercount
                    var org = OrganizationHandler.getOrganization(ContactHandler.getContact(contact.identifier).deptId);
                    if(org == null || org.membercount == null){
                        return;
                    }
                    org.membercount += 1;
                });

            }

            function updateContacts(contacts){
                angular.forEach(contacts, function (contact) {
                    ContactHandler.saveContact(contact);
                });
            }

            function deleteContacts(contacts) {
                //delete contact
                angular.forEach(contacts, function (contact) {
                    ContactHandler.deleteContact(contact.identifier);
                    //update dept membercount
                    var org = OrganizationHandler.getOrganization(ContactHandler.getContact(contact.identifier).deptId);
                    if(org == null || org.membercount == null){
                        return;
                    }
                    org.membercount -= 1;
                });
            }

            function updateGroupMessageView(message) {
                if (GroupHandler.getDeptGroupIdentifiers().contains(message.groupId)) {//部门群组加人，踢人信息不显示
                    return;
                }
                groupTipMessageFormat(message);
                //过滤历史数据
                if(message.content == null || message.content == ''){
                    return;
                }
                if (GroupHandler.groupIsExist(message.groupId)) {
                    var chatObj = ChatHandler.addChat(ChatHandler.groupCommandMessage2Chat(message));
                    webNotification(chatObj);
                } else {
                    GroupHandler.queryGroupPromise({'groupUid': message.groupId}).then(function (group) {//执行成功
                        var chatObj = ChatHandler.addChat(ChatHandler.groupCommandMessage2Chat(message));
                        webNotification(chatObj);
                    }, function (errorMessage) {//执行失败
                        swal({title: errorMessage, timer: 2000});
                        return;
                    });
                }
                if ($rootScope.voiceStatu) {
                    util.msgPlay();
                }
                if (MessageManager.isCurrChatMsg(message)) {
                    $rootScope.messages.push(message);
                }
                MessageManager.saveMessage(message);
            }

            var checkGroupTipMessage = function(message){//检查群组加，踢人提示消息
                var optUserIdentifier = message.optUser;
                var userIdentifiers = message.users;
                var optUser = ContactHandler.getContact(optUserIdentifier);
                if(optUser == null || optUser.identifier == null){
                    return false;
                }
                for(var index = 0; index < userIdentifiers.length; index++){
                    var contact = ContactHandler.getContact(userIdentifiers[index]);
                    if(contact == null || contact.identifier == null){
                        return false;
                    }
                }
                return true;
            }

            //群组加，踢人提示消息处理
            var groupTipMessageFormat = function(message){
                if(!checkGroupTipMessage(message)) return;
                var messageContent = '';
                var optUserIdentifier = message.optUser;
                var userIdentifiers = message.users;
                switch (message.commType){
                    case 52://群组加人
                        var index = 0;
                        messageContent += ContactHandler.getContact(optUserIdentifier).identifier == $rootScope.user.identifier ? '你' : ContactHandler.getContact(optUserIdentifier).name;
                        messageContent += '邀请';
                        angular.forEach(userIdentifiers, function(identifier){
                            index++;
                            messageContent += identifier == $rootScope.user.identifier?'你':ContactHandler.getContact(identifier).name;
                            if(index < userIdentifiers.length){
                                messageContent += ','
                            }
                        });
                        messageContent += '进入群聊. ';
                        break;
                    case 53://群组删人
                        messageContent += ContactHandler.getContact(optUserIdentifier).identifier == $rootScope.user.identifier ? '你' : ContactHandler.getContact(optUserIdentifier).name;
                        if(userIdentifiers.length == 1 && userIdentifiers[0] == optUserIdentifier){
                            messageContent += '已退出群聊. ';
                        }else if(userIdentifiers.length == 1 && userIdentifiers[0] == $rootScope.user.identifier){
                            messageContent += '将你移出群聊.';
                        }else{
                            var index = 0;
                            messageContent += '将';
                            angular.forEach(userIdentifiers, function (identifier) {
                                index++;
                                messageContent += ContactHandler.getContact(identifier).name;
                                if (index < userIdentifiers.length) {
                                    messageContent += ','
                                }
                            });
                            messageContent += '移出群聊. ';
                        }
                        break;
                }
                message.content = messageContent;
            }

            function addGroupContact(message){
                angular.forEach(message.users, function(identifier){
                    ContactHandler.saveGroupContact(message.groupId, identifier);
                });
                //UPDATE GROUP USER_COUNT
                var group = GroupHandler.getGroupByIdentifier(message.groupId);
                if(group == null || group.userCount == null){
                    return;
                }
                var addContactNum = message.users.length;
                group.userCount += addContactNum;
                if(group.invalid && message.users.contains($rootScope.user.identifier)){
                    group.invalid = false;//update group status
                    GroupHandler.saveGroup(group);
                }
                //UPDATE CHAT USER_COUNT
                ChatHandler.updateChat({'identifier': message.groupId, 'userCount' : group.userCount});
                updateGroupMessageView(message);
            }

            function delGroupContact(message){
                var group = GroupHandler.getGroupByIdentifier(message.groupId);
                if(group == null || group.userCount == null){
                    return;
                }
                //UPDATE CHAT USER_COUNT
                ChatHandler.updateChat({'identifier': message.groupId, 'userCount' : group.userCount});
                //判断当前用户是否被移除了群组
                var removeIds = message.users;
                if (removeIds.contains($rootScope.user.identifier)) {
                    group.invalid = true;//update group status
                    GroupHandler.saveGroup(group);
                } else {
                    angular.forEach(message.users, function (identifier) {
                        ContactHandler.deleteGroupContact(message.groupId, identifier);
                    });
                    //UPDATE GROUP USER_COUNT
                    var addContactNum = removeIds.length;
                    group.userCount -= addContactNum;
                }
                updateGroupMessageView(message);
            }

            function initView(identifier) {
           		$rootScope.messages = MessageManager.getMessages(identifier);
           		util.setProgress($rootScope.messages);
            };

            function update(message) {
                //显示发送消息加载
                message.sendState = 0;
                message.unreadMessages = 0;
                $rootScope.messages.push(message);
            }



            //桌面通知
            window.onload = function(){
                var hidden, state, visibilityChange;
                if (typeof document.hidden !== "undefined") {
                    hidden = "hidden";
                    visibilityChange = "visibilitychange";
                    state = "visibilityState";
                } else if (typeof document.mozHidden !== "undefined") {
                    hidden = "hidden";
                    visibilityChange = "mozvisibilitychange";
                    state = "mozVisibilityState";
                } else if (typeof document.msHidden !== "undefined") {
                    hidden = "hidden";
                    visibilityChange = "msvisibilitychange";
                    state = "msVisibilityState";
                } else if (typeof document.webkitHidden !== "undefined") {
                    hidden = "hidden";
                    visibilityChange = "webkitvisibilitychange";
                    state = "webkitVisibilityState";
                }

                // 添加监听器，在title里显示状态变化
                document.addEventListener(visibilityChange, function() {
                    window.pcWeb.currentPageState = document[state];
                }, false);
            }

            function webNotification(chatObj){
                setTimeout(function(){
                    if($rootScope.notification==true && window.pcWeb.currentPageState == 'hidden'){
                        var showMuteType = util.showMute(chatObj, $rootScope.allUnreadMessages);
                        if(showMuteType == false){
                            $rootScope.notification = false;
                        }
                    }
                },500);
            }

            return {
                init: initView,
                update : update,
                groupTipMessageFormat : groupTipMessageFormat,
                receive: function (message, callback) {
                	$rootScope.safeApply(function () {
                        receiveMsg(message, callback);
                    });
                }
            };
        }]);